package com.aooci.ordercat.desktop.view;

import java.io.IOException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ResourceBundle;

import org.controlsfx.dialog.Dialogs;

import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.MenuItem;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.VBox;
import javafx.scene.layout.HBox;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;

import com.aooci.ordercat.desktop.OrdercatMain;
import com.aooci.ordercat.desktop.SystemConstant;
import com.aooci.ordercat.domain.DiningTable;
import com.aooci.ordercat.enums.DiningTableStatus;
import com.aooci.ordercat.vo.OperatedOrderVo;
import com.aooci.ordercat.vo.TakeawayVo;

@SuppressWarnings("restriction")
public class DashboardController implements Initializable {

	private OrdercatMain ordercatMain;

	//private Map<Integer, Button> tableButtons;
	
	@FXML private TableView<TakeawayVo> takeawayTable;
	@FXML private TableColumn<TakeawayVo, Number> takeawayNumberColumn;
	@FXML private TableColumn<TakeawayVo, String> takeawayTakingTimeColumn;
	//private Takeaway selectedTakeaway;
	//private ObservableList<Takeaway> takeawayButtonItems;// = FXCollections.observableArrayList ();
	
	@FXML private Button closeButton;
	
	@FXML private AnchorPane diningHallPane;
	@FXML private AnchorPane terracePane;
	
	@FXML MenuItem close;
	@FXML MenuItem about;
	@FXML MenuItem accounting;
	
	private static SimpleDateFormat timeFormat = new SimpleDateFormat("dd/MM/yyyy - HH:mm");
	
	@FXML
	public void initialize(URL arg0, ResourceBundle arg1) {
		takeawayNumberColumn.setCellValueFactory(cellData -> cellData.getValue().idProperty());
		takeawayTakingTimeColumn.setCellValueFactory(cellData -> cellData.getValue().takingTimeStrProperty());

		this.takeawayTable.getStyleClass().add("takeaway_list");
		
		this.close.setOnAction((event) -> {
			ordercatMain.getPrimaryStage().close();
		});
		this.about.setOnAction((event) -> {
			Dialogs.create().lightweight()
	        .owner(ordercatMain.getPrimaryStage())
	        .title("About")
	        .message("Order Cat Resaurant Management System\n"
	        		+"Version: 1.0 \n"
	        		+"Technical support: pangbuddy@gmail.com")
	        .showInformation();
		});
		
		this.accounting.setOnAction((event) -> {
			try {
				FXMLLoader loader = new FXMLLoader();
				loader.setLocation(OrdercatMain.class.getResource(SystemConstant.ACCOUNTING_FXML));
				HBox page = (HBox) loader.load();

				Stage dialogStage = new Stage();
				dialogStage.initStyle(StageStyle.UNDECORATED);
				dialogStage.setTitle(SystemConstant.ACCOUNTING_TITLE);
				dialogStage.initModality(Modality.APPLICATION_MODAL);
				dialogStage.initOwner(this.ordercatMain.getPrimaryStage());
				dialogStage.setResizable(true);
				dialogStage.setFocused(true);
				
				Scene scene = new Scene(page);
				dialogStage.setScene(scene);
				scene.getStylesheets().add("css/desktop.css");
				AccountingController controller = loader.getController();
				controller.init(ordercatMain);
				//controller.init(ordercatMain, dialogStage, operatedOrderVo, takeawayTable);
				dialogStage.showAndWait();
			} catch (IOException e) {
				e.printStackTrace();
			}
		});
	}
	
	public void init(OrdercatMain ordercatMain){
		this.ordercatMain = ordercatMain;
		
		
		//Takeaway list
		//List<Takeaway> list = this.ordercatMain.getDashboardService().loadNoFreeTakeaways();
		//takeawayButtonItems = FXCollections.observableArrayList (list);
		this.takeawayTable.setItems(FXCollections.observableArrayList (this.ordercatMain.getDashboardService().loadNoFreeTakeaways()));
		 
		//this.ordercatMain.setTakeawayButtons(takeawayButtons);

		//Dining Hall table buttons list
		int lx = 20;
		int ly = 20;
		for(DiningTable table : this.ordercatMain.getDashboardService().loadDiningTablesByCategoryId(1)){
			Button button = new Button();
			button.getStyleClass().add("table_button");
			button.setText(table.getLabel());
			button.setLayoutX(lx);
			button.setLayoutY(ly);
			
			if(DiningTableStatus.FREE.equals(table.getStatus())){
				button.getStyleClass().add("dininghall_free_table");
			}else if(DiningTableStatus.OCCUPIED.equals(table.getStatus())){
				button.getStyleClass().add("dininghall_occupied_table");
			}else if(DiningTableStatus.PAID.equals(table.getStatus())){
				button.getStyleClass().add("dininghall_paid_table");
			}
			
			button.setOnAction(new EventHandler<ActionEvent>() {
			    @Override public void handle(ActionEvent e) {
			    	DiningTable selectedTable = ordercatMain.getDashboardService().loadDiningTableById(table.getId());
			    	
					if(DiningTableStatus.FREE.equals(selectedTable.getStatus())){
						selectNofClient(selectedTable, button);
					}else if(DiningTableStatus.OCCUPIED.equals(selectedTable.getStatus())){
						OperatedOrderVo operatedOrderVo = ordercatMain.getOrderOperationService().loadDiningTableOrder(selectedTable.getId());
				    	openOrderOperationDialog(operatedOrderVo);
					}else if(DiningTableStatus.PAID.equals(selectedTable.getStatus())){
						OperatedOrderVo operatedOrderVo = ordercatMain.getOrderOperationService().loadDiningTableOrder(selectedTable.getId());
				    	openOrderOperationDialog(operatedOrderVo);
					}
			    }
			});
			
			
			if(lx < 600){
				lx += 120;
			}else{
				lx = 20;
				ly += 110;
				
			}
			this.diningHallPane.getChildren().add(button);
			this.ordercatMain.getDiningHallTables().put(table.getId(), button);
		}
		
		//Terrace table buttons list
//		lx = 20;
//		ly = 50;
//		for(DiningTable table : this.ordercatMain.getDashboardService().loadDiningTablesByCategoryId(3)){
//			Button button = new Button();
//			button.setText(table.getLabel());
//			button.setFont(Font.font ("System", 18));
//			button.setPrefWidth(100);
//			button.setPrefHeight(60);
//			button.setLayoutX(lx);
//			button.setLayoutY(ly);
//			
//			if(lx < 600){
//				lx += 120;
//			}else{
//				lx = 20;
//				ly += 100;
//			}
//			this.terracePane.getChildren().add(button);
//		}
	}
	
	@FXML public void handleMouseClickOnTakeawayButtons(MouseEvent arg0) {
	    System.out.println("clicked on " + this.takeawayTable.getSelectionModel().getSelectedItem());

	    this.openOrderOperationDialog( this.ordercatMain.getOrderOperationService().loadTakeawayOrder(this.takeawayTable.getSelectionModel().getSelectedItem().getId()));
	}
	
    public void closePanel() {
        ((Stage) this.closeButton.getScene().getWindow()).close();
    }
	
	@SuppressWarnings("deprecation")
	@FXML
    private void newTakeaway() {
		
		try {
			// Load the fxml file and create a new stage for the popup dialog.
			FXMLLoader loader = new FXMLLoader();
			loader.setLocation(OrdercatMain.class.getResource(SystemConstant.NEW_TAKEAWAY_PANEL_FXML));
			AnchorPane page = (AnchorPane) loader.load();

			// Create the dialog Stage.
			Stage dialogStage = new Stage();
			dialogStage.setTitle(SystemConstant.NEW_TAKEAWAY_PANEL_TITLE);
			dialogStage.initModality(Modality.WINDOW_MODAL);
			dialogStage.initOwner(this.ordercatMain.getPrimaryStage());
			dialogStage.setResizable(false);
			dialogStage.setFocused(true);
			Scene scene = new Scene(page);
			dialogStage.setScene(scene);

			// Set the person into the controller.
			NewTakeawayPanelController controller = loader.getController();
			controller.setOrdercatMain(this.ordercatMain);
			//controller.setTakeawayTable(takeawayTable);
			controller.setDashboardController(this);
			// Show the dialog and wait until the user closes it
			dialogStage.showAndWait();

			//return controller.isOkClicked();
		} catch (IOException e) {
			e.printStackTrace();
		}
    }
	
	@SuppressWarnings("deprecation")
	public void openOrderOperationDialog(OperatedOrderVo operatedOrderVo){
		try {
			FXMLLoader loader = new FXMLLoader();
			loader.setLocation(OrdercatMain.class.getResource(SystemConstant.ORDER_OPERATIONL_FXML));
			VBox page = (VBox) loader.load();

			Stage dialogStage = new Stage();
			dialogStage.initStyle(StageStyle.UNDECORATED);
			dialogStage.setTitle(SystemConstant.ORDER_OPERATION_TITLE);
			dialogStage.initModality(Modality.APPLICATION_MODAL);
			dialogStage.initOwner(this.ordercatMain.getPrimaryStage());
			dialogStage.setResizable(true);
			dialogStage.setFocused(true);
			
			Scene scene = new Scene(page);
			dialogStage.setScene(scene);
			scene.getStylesheets().add("css/desktop.css");
			OrderOperationController controller = loader.getController();
			controller.init(ordercatMain, dialogStage, operatedOrderVo, takeawayTable);
			dialogStage.showAndWait();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@FXML
    private void selectNofClient(DiningTable table, Button button) {
		try {
			// Load the fxml file and create a new stage for the popup dialog.
			FXMLLoader loader = new FXMLLoader();
			loader.setLocation(OrdercatMain.class.getResource(SystemConstant.SELECT_NOF_CLIENT_PANEL_FXML));
			GridPane page = (GridPane) loader.load();

			// Create the dialog Stage.
			Stage dialogStage = new Stage();
			dialogStage.setTitle(SystemConstant.SELECT_NOF_CLIENT_PANEL_TITLE + " Table: " + table.getLabel());
			dialogStage.initModality(Modality.WINDOW_MODAL);
			dialogStage.initOwner(this.ordercatMain.getPrimaryStage());
			dialogStage.setResizable(false);
			dialogStage.setFocused(true);
			Scene scene = new Scene(page);
			dialogStage.setScene(scene);

			// Set the person into the controller.
			SelectingNofClientPanelController controller = loader.getController();
			controller.setOrdercatMain(this.ordercatMain);
			controller.setDashboardController(this);
			controller.setTable(table);
			controller.setButton(button);

			// Show the dialog and wait until the user closes it
			dialogStage.showAndWait();

			//return controller.isOkClicked();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		
        //return new SelectingNofClientPanel(this.ordercatMain.getPrimaryStage());
    }

	public TableView<TakeawayVo> getTakeawayTable() {
		return takeawayTable;
	}

}
